In [3]:
import networkx as nx
from datetime import datetime
import matplotlib.pyplot as plt
import numpy as np

%matplotlib inline

Nodes and Edges: How do we represent relationships between individuals using NetworkX?

As mentioned earlier, networks, also known as graphs, are comprised of individual entities and their representatives. The technical term for these are nodes and edges, and when we draw them we typically use circles (nodes) and lines (edges).

In this notebook, we will work with a synthetic (i.e. simulated) social network, in which nodes are individual people, and edges represent their relationships. If two nodes have an edge between them, then those two individauls know one another.

Data Representation

In the networkx implementation, graph objects store their data in dictionaries.

Nodes are part of the attribute Graph.node, which is a dictionary where the key is the node ID and the values are a dictionary of attributes.

Edges are part of the attribute Graph.edge, which is a nested dictionary. Data are accessed as such: G.edge[node1][node2]['attr_name'].

Because of the dictionary implementation of the graph, any hashable object can be a node. This means strings and tuples, but not lists and sets.

Synthetic Social Network

With this synthetic social network, we will attempt to answer the following basic questions using the NetworkX API:

  1. How many people are present in the network?
  2. What is the distribution of attributes of the people in this network?
  3. How many relationships are represented in the network?
  4. What is the distribution of the number of friends that each person has?

First off, let's load up the synthetic social network. This will show you through some of the basics of NetworkX.

For those who are interested, I simply created an Erdõs-Rényi graph with n=30 and p=0.1. I used randomized functions that I wrote to generate attributes and append them to each node and edge. I then pickled the graph to disk.


In [4]:
G = nx.read_gpickle('Synthetic Social Network.pkl') #If you are Python 2.7, read in Synthetic Social Network 27.pkl
nx.draw(G)


Basic Network Statistics

Let's first understand how many people and relationships are represented in the network.


In [5]:
# Who are represented in the network?
G.nodes(data=True)


Out[5]:
[(0, {'age': 20, 'sex': 'Male'}),
 (1, {'age': 21, 'sex': 'Female'}),
 (2, {'age': 19, 'sex': 'Male'}),
 (3, {'age': 29, 'sex': 'Female'}),
 (4, {'age': 30, 'sex': 'Male'}),
 (5, {'age': 26, 'sex': 'Female'}),
 (6, {'age': 21, 'sex': 'Male'}),
 (7, {'age': 17, 'sex': 'Female'}),
 (8, {'age': 21, 'sex': 'Male'}),
 (9, {'age': 14, 'sex': 'Male'}),
 (10, {'age': 23, 'sex': 'Male'}),
 (11, {'age': 17, 'sex': 'Female'}),
 (12, {'age': 19, 'sex': 'Male'}),
 (13, {'age': 27, 'sex': 'Female'}),
 (14, {'age': 29, 'sex': 'Female'}),
 (15, {'age': 14, 'sex': 'Male'}),
 (16, {'age': 18, 'sex': 'Female'}),
 (17, {'age': 21, 'sex': 'Female'}),
 (18, {'age': 19, 'sex': 'Male'}),
 (19, {'age': 19, 'sex': 'Female'}),
 (20, {'age': 19, 'sex': 'Female'}),
 (21, {'age': 21, 'sex': 'Male'}),
 (22, {'age': 30, 'sex': 'Female'}),
 (23, {'age': 25, 'sex': 'Female'}),
 (24, {'age': 13, 'sex': 'Male'}),
 (25, {'age': 24, 'sex': 'Female'}),
 (26, {'age': 23, 'sex': 'Male'}),
 (27, {'age': 21, 'sex': 'Male'}),
 (28, {'age': 29, 'sex': 'Female'}),
 (29, {'age': 25, 'sex': 'Male'})]

Exercise: Can you write a single line of code that returns the number of individuals represented?


In [6]:
len(G.nodes())


Out[6]:
30

In [7]:
# Who is connected to who in the network?
G.edges(data=True)


Out[7]:
[(0, 10, {'date': datetime.datetime(2011, 6, 7, 0, 0)}),
 (0, 19, {'date': datetime.datetime(2011, 2, 12, 0, 0)}),
 (0, 12, {'date': datetime.datetime(2006, 8, 28, 0, 0)}),
 (1, 4, {'date': datetime.datetime(2009, 11, 8, 0, 0)}),
 (1, 2, {'date': datetime.datetime(2010, 8, 5, 0, 0)}),
 (1, 3, {'date': datetime.datetime(2005, 2, 3, 0, 0)}),
 (1, 12, {'date': datetime.datetime(2003, 3, 17, 0, 0)}),
 (1, 29, {'date': datetime.datetime(2005, 1, 15, 0, 0)}),
 (2, 16, {'date': datetime.datetime(2002, 5, 27, 0, 0)}),
 (2, 3, {'date': datetime.datetime(2009, 8, 13, 0, 0)}),
 (2, 6, {'date': datetime.datetime(2006, 1, 12, 0, 0)}),
 (2, 19, {'date': datetime.datetime(2010, 1, 6, 0, 0)}),
 (3, 8, {'date': datetime.datetime(2010, 6, 22, 0, 0)}),
 (3, 6, {'date': datetime.datetime(2009, 3, 20, 0, 0)}),
 (3, 23, {'date': datetime.datetime(2003, 11, 9, 0, 0)}),
 (4, 19, {'date': datetime.datetime(2007, 12, 4, 0, 0)}),
 (4, 28, {'date': datetime.datetime(2009, 5, 22, 0, 0)}),
 (6, 23, {'date': datetime.datetime(2011, 3, 4, 0, 0)}),
 (7, 24, {'date': datetime.datetime(2004, 9, 24, 0, 0)}),
 (7, 25, {'date': datetime.datetime(2009, 3, 21, 0, 0)}),
 (8, 17, {'date': datetime.datetime(2005, 11, 16, 0, 0)}),
 (8, 22, {'date': datetime.datetime(2010, 1, 22, 0, 0)}),
 (9, 24, {'date': datetime.datetime(2008, 12, 2, 0, 0)}),
 (9, 17, {'date': datetime.datetime(2009, 10, 11, 0, 0)}),
 (9, 11, {'date': datetime.datetime(2005, 4, 3, 0, 0)}),
 (10, 11, {'date': datetime.datetime(2005, 2, 6, 0, 0)}),
 (10, 21, {'date': datetime.datetime(2007, 1, 21, 0, 0)}),
 (11, 14, {'date': datetime.datetime(2010, 4, 28, 0, 0)}),
 (12, 19, {'date': datetime.datetime(2007, 12, 17, 0, 0)}),
 (12, 29, {'date': datetime.datetime(2008, 8, 27, 0, 0)}),
 (13, 16, {'date': datetime.datetime(2005, 5, 14, 0, 0)}),
 (13, 24, {'date': datetime.datetime(2006, 5, 7, 0, 0)}),
 (13, 14, {'date': datetime.datetime(2011, 3, 19, 0, 0)}),
 (14, 17, {'date': datetime.datetime(2008, 10, 17, 0, 0)}),
 (14, 25, {'date': datetime.datetime(2002, 6, 11, 0, 0)}),
 (15, 24, {'date': datetime.datetime(2007, 9, 2, 0, 0)}),
 (15, 28, {'date': datetime.datetime(2008, 3, 6, 0, 0)}),
 (16, 17, {'date': datetime.datetime(2002, 5, 20, 0, 0)}),
 (16, 19, {'date': datetime.datetime(2005, 8, 20, 0, 0)}),
 (17, 19, {'date': datetime.datetime(2006, 10, 13, 0, 0)}),
 (19, 22, {'date': datetime.datetime(2011, 11, 4, 0, 0)}),
 (19, 27, {'date': datetime.datetime(2009, 7, 27, 0, 0)}),
 (20, 27, {'date': datetime.datetime(2004, 1, 27, 0, 0)}),
 (20, 23, {'date': datetime.datetime(2007, 12, 3, 0, 0)}),
 (21, 27, {'date': datetime.datetime(2007, 2, 1, 0, 0)}),
 (21, 26, {'date': datetime.datetime(2006, 12, 14, 0, 0)}),
 (25, 28, {'date': datetime.datetime(2007, 2, 15, 0, 0)}),
 (26, 29, {'date': datetime.datetime(2006, 12, 19, 0, 0)})]

Exercise

Can you write a single line of code that returns the number of relationships represented?


In [8]:
len(G.edges())


Out[8]:
48

Since this is a social network of people, there'll be attributes for each individual, such as age, and sex. We can grab that data off from the attributes that are stored with each node.


In [9]:
# Let's get a list of nodes with their attributes.
G.nodes(data=True)

# NetworkX will return a list of tuples in the form (node_id, attribute_dictionary)


Out[9]:
[(0, {'age': 20, 'sex': 'Male'}),
 (1, {'age': 21, 'sex': 'Female'}),
 (2, {'age': 19, 'sex': 'Male'}),
 (3, {'age': 29, 'sex': 'Female'}),
 (4, {'age': 30, 'sex': 'Male'}),
 (5, {'age': 26, 'sex': 'Female'}),
 (6, {'age': 21, 'sex': 'Male'}),
 (7, {'age': 17, 'sex': 'Female'}),
 (8, {'age': 21, 'sex': 'Male'}),
 (9, {'age': 14, 'sex': 'Male'}),
 (10, {'age': 23, 'sex': 'Male'}),
 (11, {'age': 17, 'sex': 'Female'}),
 (12, {'age': 19, 'sex': 'Male'}),
 (13, {'age': 27, 'sex': 'Female'}),
 (14, {'age': 29, 'sex': 'Female'}),
 (15, {'age': 14, 'sex': 'Male'}),
 (16, {'age': 18, 'sex': 'Female'}),
 (17, {'age': 21, 'sex': 'Female'}),
 (18, {'age': 19, 'sex': 'Male'}),
 (19, {'age': 19, 'sex': 'Female'}),
 (20, {'age': 19, 'sex': 'Female'}),
 (21, {'age': 21, 'sex': 'Male'}),
 (22, {'age': 30, 'sex': 'Female'}),
 (23, {'age': 25, 'sex': 'Female'}),
 (24, {'age': 13, 'sex': 'Male'}),
 (25, {'age': 24, 'sex': 'Female'}),
 (26, {'age': 23, 'sex': 'Male'}),
 (27, {'age': 21, 'sex': 'Male'}),
 (28, {'age': 29, 'sex': 'Female'}),
 (29, {'age': 25, 'sex': 'Male'})]

Exercise

Can you count how many males and females are represented in the graph?

Hint: You may want to use the Counter object from the collections module.


In [10]:
from collections import Counter
Counter([d['sex'] for n, d in G.nodes(data=True)])


Out[10]:
Counter({'Female': 15, 'Male': 15})

Edges can also store attributes in their attribute dictionary.


In [11]:
G.edges(data=True)


Out[11]:
[(0, 10, {'date': datetime.datetime(2011, 6, 7, 0, 0)}),
 (0, 19, {'date': datetime.datetime(2011, 2, 12, 0, 0)}),
 (0, 12, {'date': datetime.datetime(2006, 8, 28, 0, 0)}),
 (1, 4, {'date': datetime.datetime(2009, 11, 8, 0, 0)}),
 (1, 2, {'date': datetime.datetime(2010, 8, 5, 0, 0)}),
 (1, 3, {'date': datetime.datetime(2005, 2, 3, 0, 0)}),
 (1, 12, {'date': datetime.datetime(2003, 3, 17, 0, 0)}),
 (1, 29, {'date': datetime.datetime(2005, 1, 15, 0, 0)}),
 (2, 16, {'date': datetime.datetime(2002, 5, 27, 0, 0)}),
 (2, 3, {'date': datetime.datetime(2009, 8, 13, 0, 0)}),
 (2, 6, {'date': datetime.datetime(2006, 1, 12, 0, 0)}),
 (2, 19, {'date': datetime.datetime(2010, 1, 6, 0, 0)}),
 (3, 8, {'date': datetime.datetime(2010, 6, 22, 0, 0)}),
 (3, 6, {'date': datetime.datetime(2009, 3, 20, 0, 0)}),
 (3, 23, {'date': datetime.datetime(2003, 11, 9, 0, 0)}),
 (4, 19, {'date': datetime.datetime(2007, 12, 4, 0, 0)}),
 (4, 28, {'date': datetime.datetime(2009, 5, 22, 0, 0)}),
 (6, 23, {'date': datetime.datetime(2011, 3, 4, 0, 0)}),
 (7, 24, {'date': datetime.datetime(2004, 9, 24, 0, 0)}),
 (7, 25, {'date': datetime.datetime(2009, 3, 21, 0, 0)}),
 (8, 17, {'date': datetime.datetime(2005, 11, 16, 0, 0)}),
 (8, 22, {'date': datetime.datetime(2010, 1, 22, 0, 0)}),
 (9, 24, {'date': datetime.datetime(2008, 12, 2, 0, 0)}),
 (9, 17, {'date': datetime.datetime(2009, 10, 11, 0, 0)}),
 (9, 11, {'date': datetime.datetime(2005, 4, 3, 0, 0)}),
 (10, 11, {'date': datetime.datetime(2005, 2, 6, 0, 0)}),
 (10, 21, {'date': datetime.datetime(2007, 1, 21, 0, 0)}),
 (11, 14, {'date': datetime.datetime(2010, 4, 28, 0, 0)}),
 (12, 19, {'date': datetime.datetime(2007, 12, 17, 0, 0)}),
 (12, 29, {'date': datetime.datetime(2008, 8, 27, 0, 0)}),
 (13, 16, {'date': datetime.datetime(2005, 5, 14, 0, 0)}),
 (13, 24, {'date': datetime.datetime(2006, 5, 7, 0, 0)}),
 (13, 14, {'date': datetime.datetime(2011, 3, 19, 0, 0)}),
 (14, 17, {'date': datetime.datetime(2008, 10, 17, 0, 0)}),
 (14, 25, {'date': datetime.datetime(2002, 6, 11, 0, 0)}),
 (15, 24, {'date': datetime.datetime(2007, 9, 2, 0, 0)}),
 (15, 28, {'date': datetime.datetime(2008, 3, 6, 0, 0)}),
 (16, 17, {'date': datetime.datetime(2002, 5, 20, 0, 0)}),
 (16, 19, {'date': datetime.datetime(2005, 8, 20, 0, 0)}),
 (17, 19, {'date': datetime.datetime(2006, 10, 13, 0, 0)}),
 (19, 22, {'date': datetime.datetime(2011, 11, 4, 0, 0)}),
 (19, 27, {'date': datetime.datetime(2009, 7, 27, 0, 0)}),
 (20, 27, {'date': datetime.datetime(2004, 1, 27, 0, 0)}),
 (20, 23, {'date': datetime.datetime(2007, 12, 3, 0, 0)}),
 (21, 27, {'date': datetime.datetime(2007, 2, 1, 0, 0)}),
 (21, 26, {'date': datetime.datetime(2006, 12, 14, 0, 0)}),
 (25, 28, {'date': datetime.datetime(2007, 2, 15, 0, 0)}),
 (26, 29, {'date': datetime.datetime(2006, 12, 19, 0, 0)})]

In this synthetic social network, I have stored the date as a datetime object. Datetime objects have attributes, namely .year, .month, .day.

Exercise

Can you figure out the range of dates during which these relationships were forged?


In [12]:
# Answer
dates = [d['date'] for _, _, d in G.edges(data=True)]
mindate = min(dates)
maxdate = max(dates)
print(mindate, maxdate)


2002-05-20 00:00:00 2011-11-04 00:00:00

Exercise

We found out that there are two individuals that we left out of the network, individual no. 31 and 32. They are one male (31) and one female (32), their ages are 22 and 24 respectively, they knew each other on 2010-01-09, and together, they both knew individual 7, on 2009-12-11. Use the functions G.add_node() and G.add_edge() to introduce this data into the network.

If you need more help, check out https://networkx.github.io/documentation/latest/tutorial/tutorial.html


In [13]:
# Answer
G.add_node(31, age=22, sex='Male')
G.add_node(32, age=24, sex='Female')
G.add_edge(31, 32, date=datetime(2010,1,9))
G.add_edge(31, 7, date=datetime(2009,12,11))
G.add_edge(32, 7, date=datetime(2009,12,11))

G.node[31]


Out[13]:
{'age': 22, 'sex': 'Male'}

Live Exercise

While we're on the matter of graph construction, let's take a look at our tutorial class. On your sheet of paper, you should have a list of names - these are people for which you knew their name prior to coming to class.

As we iterate over the class, I would like you to holler out your name, your nationality, and in a very slow fashion, the names of the people who you knew in the class.


In [14]:
ptG = nx.DiGraph() #ptG stands for PyCon Tutorial Graph.

# Add in nodes and edges
ptG.add_node('Eric', nationality='Canada')
ptG.add_node('Paul', nationality='Canada') # (my own TextExpander shortcut is ;addnode)
ptG.add_node('Max', nationality='US')
ptG.add_node('Martin', nationality='Other')
ptG.add_node('Jim', nationality='US')
ptG.add_node('Lucas', nationality='US')
ptG.add_node('Thomas', nationality='US')
ptG.add_node('Brad', nationality='US')
ptG.add_node('Troy', nationality='Canada')
ptG.add_node('Cory', nationality='Canada')
ptG.add_node('Gokhan', nationality='US')
ptG.add_node('Riley', nationality='US')
ptG.add_node('Steve', nationality='US')
ptG.add_node('Ryan', nationality='US')
ptG.add_node('Andrew', nationality='US')
ptG.add_node('Ronan', nationality='Other')
ptG.add_node('Cody', nationality='Canada')
ptG.add_node('Jon', nationality='US')
ptG.add_node('Eric2', nationality='US')
ptG.add_node('William', nationality='US')
ptG.add_node('Tom', nationality='Other')
ptG.add_node('Chris', nationality='US')
ptG.add_node('Stu', nationality='US')
ptG.add_node('Zach', nationality='US')
ptG.add_node('Clint', nationality='Canada')
ptG.add_node('Aaron', nationality='US')
ptG.add_node('Vishal', nationality='US')
ptG.add_node('Federico', nationality='Other')

ptG.add_edge('Vishal', 'Aaron')
ptG.add_edge('Vishal', 'Eric')
ptG.add_edge('Aaron', 'Vishal')
ptG.add_edge('Aaron', 'Eric')
ptG.add_edge('Clint', 'Zach')
ptG.add_edge('Clint', 'Eric')
ptG.add_edge('Zach', 'Clint')
ptG.add_edge('Zach', 'Riley')
ptG.add_edge('Zach', 'Stu')
ptG.add_edge('Stu', 'Zach')
ptG.add_edge('Stu', 'Eric')
ptG.add_edge('Stu', 'Chris')
ptG.add_edge('Chris', 'Stu')
ptG.add_edge('Chris', 'Eric')
ptG.add_edge('Tom', 'Tom')
ptG.add_edge('William', 'Jon')
ptG.add_edge('William', 'Eric2')
ptG.add_edge('William', 'Eric')
ptG.add_edge('Eric2', 'William')
ptG.add_edge('Eric2', 'Jon')
ptG.add_edge('Jon', 'Eric2')
ptG.add_edge('Jon', 'William')
ptG.add_edge('Jon', 'Eric')
ptG.add_edge('Cody', 'Eric')
ptG.add_edge('Cody', 'Ronan')
ptG.add_edge('Ronan', 'Eric')
ptG.add_edge('Ronan', 'Cody')
ptG.add_edge('Andrew', 'Eric')
ptG.add_edge('Andrew', 'Ryan')
ptG.add_edge('Ryan', 'Eric')
ptG.add_edge('Ryan', 'Andrew')
ptG.add_edge('Steve', 'Eric')
ptG.add_edge('Riley', 'Zach')
ptG.add_edge('Paul', 'Paul') # (my own TextExpander shortcut is ;addedge)
ptG.add_edge('Martin', 'Max')
ptG.add_edge('Max', 'Paul')
ptG.add_edge('Martin', 'Eric')
ptG.add_edge('Martin', 'Max')
ptG.add_edge('Jim', 'Federico')
ptG.add_edge('Lucas', 'Thomas')
ptG.add_edge('Brad', 'Eric')
ptG.add_edge('Thomas', 'Lucas')
ptG.add_edge('Troy', 'Cory')
ptG.add_edge('Troy', 'Eric')
ptG.add_edge('Cory', 'Troy')
ptG.add_edge('Gokhan', 'Max')

In [16]:
# We are now going to draw the network using a hive plot, grouping the nodes by the top two nationality groups, and 'others'
# for the third group.

nodes = dict()
nodes['Canada'] = [n for n, d in ptG.nodes(data=True) if d['nationality'] == 'Canada'] #list comprehension here
nodes['US'] = [n for n, d in ptG.nodes(data=True) if d['nationality'] == 'US'] #list comprehension here
nodes['Other'] = [n for n, d in ptG.nodes(data=True) if d['nationality'] == 'Other'] #list comprehension here

edges = dict()
edges['group1'] = [(n1, n2, d) for n1, n2, d in ptG.edges(data=True)] #list comprehension here

nodes_cmap = dict()
nodes_cmap['Canada'] = 'blue'
nodes_cmap['US'] = 'green'
nodes_cmap['Other'] = 'black'

edges_cmap = dict()
edges_cmap['group1'] = 'black'

from hiveplot import HivePlot
h = HivePlot(nodes, edges, nodes_cmap, edges_cmap)
h.set_minor_angle(np.pi / 12) #optional
h.draw()


Coding Patterns

These are some recommended coding patterns when doing network analysis using NetworkX, which stem from my roughly two years of experience with the package.

Iterating using List Comprehensions

I would recommend that you use the following for compactness:

[d['attr'] for n, d in G.nodes(data=True)]

And if the node is unimportant, you can do:

[d['attr'] for _, d in G.nodes(data=True)]

Iterating over Edges using List Comprehensions

A similar pattern can be used for edges:

[n2 for n1, n2, d in G.edges(data=True)]

or

[n2 for _, n2, d in G.edges(data=True)]

If the graph you are constructing is a directed graph, with a "source" and "sink" available, then I would recommend the following pattern:

[(sc, sk) for sc, sk, d in G.edges(data=True)]

or

[d['attr'] for sc, sk, d in G.edges(data=True)]

Drawing Graphs

As illustrated above, we can draw graphs using the nx.draw() function. The most popular format for drawing graphs is the node-link diagram.


In [17]:
nx.draw(G)


If the network is small enough to visualize, and the node labels are small enough to fit in a circle, then you can use the with_labels=True argument.


In [18]:
nx.draw(G, with_labels=True)


However, note that if the number of nodes in the graph gets really large, node-link diagrams can begin to look like massive hairballs. This is undesirable for graph visualization.

Instead, we can use a matrix to represent them. The nodes are on the x- and y- axes, and a filled square represent an edge between the nodes. This is done by using the nx.to_numpy_matrix(G) function.

We then use matplotlib's pcolor(numpy_array) function to plot. Because pcolor cannot take in numpy matrices, we will cast the matrix as an array of arrays, and then get pcolor to plot it.


In [19]:
matrix = nx.to_numpy_matrix(G)

plt.pcolor(np.array(matrix))
plt.axes().set_aspect('equal') # set aspect ratio equal to get a square visualization
plt.xlim(min(G.nodes()), max(G.nodes())) # set x and y limits to the number of nodes present.
plt.ylim(min(G.nodes()), max(G.nodes()))
plt.title('Adjacency Matrix')
plt.show()


Let's try another visualization, the Circos plot. We can order the nodes in the Circos plot according to the node ID, but any other ordering is possible as well. Edges are drawn between two nodes.

Credit goes to Justin Zabilansky (MIT) for the implementation.


In [20]:
from circos import CircosPlot

fig = plt.figure(figsize=(6,6))
ax = fig.add_subplot(111)

nodes = sorted(G.nodes())
edges = G.edges()

c = CircosPlot(nodes, edges, radius=10, ax=ax)
c.draw()


<matplotlib.figure.Figure at 0x108699518>

It's pretty obvious in this visualization that there are nodes, such as node 5 and 18, that are not connected to any other node via an edge. There are other nodes, like node number 19, which is highly connected to other nodes.

Finally, let's try hive plots for the network. Two groups (male and female), and then edges drawn between them.


In [21]:
nodes = dict()
nodes['male'] = [n for n,d in G.nodes(data=True) if d['sex'] == 'Male']
nodes['female'] = [n for n,d in G.nodes(data=True) if d['sex'] == 'Female']

edges = dict()
edges['group1'] = G.edges(data=True)

nodes_cmap = dict()
nodes_cmap['male'] = 'blue'
nodes_cmap['female'] = 'red'

edges_cmap = dict()
edges_cmap['group1'] = 'black'

h = HivePlot(nodes, edges, nodes_cmap, edges_cmap)
h.draw()



In [ ]:


In [ ]: